#include "Config.h"
#include "INIReader.h"

INIReader::INIReader( const std::string& file_, char ft_, char lt_, char ec_ )
	: _ft( ft_ ), _lt( lt_ ), _ec( ec_ ), _file( file_ )
{
}

bool INIReader::prepare()
{
	_ifs.open( _file, std::ifstream::in );
	if ( !_ifs )
		return false;
	std::string line;
	while ( !_ifs.eof() )
	{
		std::getline( _ifs, line, _lt );
		if ( line.empty() )
			continue;
		size_t fpos = line.find_first_of( ',' );
		if ( fpos == std::string::npos )
			continue;
		std::string key = line.substr( 0, fpos );
		std::string value = line.substr( ++ fpos );
		ASSERT( _values.find( key ) == _values.end() );
		if ( !value.empty() )
		{
			if ( *value.begin() == _ec )
				value.erase( value.begin() );
			if ( !value.empty() )
			{
				auto lastItr = value.begin() + value.size() - 1;
				if ( *lastItr == _ec )
					value.erase( lastItr );
			}
		}
		_values.insert( std::make_pair( key, value ) );
	}
	return true;
}

const std::string& INIReader::fetch( const std::string& field )
{
	static const std::string null;
	auto found = _values.find( field );
	return found == _values.end() ? null : found->second;
}

void INIReader::over()
{
	_ifs.close();
}